
import './RolePermissions.scss'

import { Button, Tree, App } from 'antd'
import { useRequest } from 'alova/client'
import { useMount } from 'ahooks'
import { useState } from 'react'

import { Http } from '../../Utils/Api'


const RolePermissions = ({ data, Off }) => {
    const { notification } = App.useApp()
    const { init } = data
    const [Menu, setMenu] = useState()
    const [Role, setRole] = useState()
    const { send } = useRequest(({ url, params }) => Http({ url, params }), { immediate: false })

    useMount(async () => {
        const menu = await send({ url: 'getRoleMenuListByUserUuid' })
        const role = await send({ url: 'getRoleMenuListByRole', params: { RoleUuid: init.uuid } })
        const menuList = JSON.parse(JSON.stringify(menu.data.list).replace(/uuid/g, 'key').replace(/tableName/g, 'title'))
        setMenu(menuList)
        setRole(role.data || [])
    })

    const onSubmit = () => {
        const params = Role.map(key => ({ roleUuid: init.uuid, menuUuid: key }))
        send({ url: 'posRoleMenu', params }).then(res => {
            notification.success({ key: 'fromModify', message: res.message, description: '角色权限已修改' })
            Off()
        })
    }

    return (
        <div className='RolePermissions'>
            <div className='Tree'>
                {Menu && Role &&
                    <Tree
                        selectable={false}
                        checkable
                        blockNode
                        defaultExpandAll
                        defaultCheckedKeys={Role}
                        treeData={Menu}
                        onCheck={setRole}
                        titleRender={e => <div>{e.title} {e.remark && `(${e.remark})`}</div>}
                    />
                }
            </div>
            <div className='Button'>
                <Button type='primary' size='large' onClick={onSubmit}>保存</Button>
            </div>
        </div>
    );
};

export default RolePermissions;